<template>
  <div>
    <div class="share" v-show="len <= 0">
      <div class="share-box">
        <div class="share-left">
          <el-tabs type="border-card">
            <el-tab-pane label="选择指数成分股">
              <el-select
                v-model="indexCode"
                filterable
                remote
                reserve-keyword
                placeholder="请选择"
                remote-show-suffix
                :remote-method="indexCodeQuery"
                @change="indexCodeChange"
              >
                <el-option
                  v-for="item in indexCodeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
              <div class="copy" @click="addAllCustomerList">
                <svg-icon name="copy"></svg-icon>
                <span> 批量添加入自定义股票池 </span>
              </div>
              <div>
                <el-table
                  :data="indexList"
                  style="width: 100%"
                  height="380"
                  stripe
                  ref="tableRef"
                  @selection-change="handleSelectionChange"
                  @scroll="handleScroll"
                  @sort-change="handleSortChange"
                >
                  <el-table-column type="selection" width="45"> </el-table-column>
                  <el-table-column prop="sConIrdcode" label="股票代码" align="center">
                  </el-table-column>
                  <el-table-column prop="sConIrdname" label="股票名称" align="center">
                  </el-table-column>
                  <el-table-column prop="iWeight" label="净占比" sortable="custom" align="center">
                    <template #default="scope">
                      {{ fix2(scope?.row?.iWeight) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template v-slot="scope">
                      <el-button type="text" @click="addCustomerList(scope.row)">添加</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 加载提示 -->
                <div v-if="selectLoading" style="text-align: center; padding: 10px">
                  <el-icon><Loading /></el-icon>
                  <span>加载中...</span>
                </div>
                <div v-if="selectNoMore" style="text-align: center; padding: 10px">
                  <span>没有更多数据了</span>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="自定义查找">
              <div class="custom-search">
                <div class="custom-search-title">
                  <span>添加股票入自定义股票池</span>
                </div>
                <div class="custom-search-input">
                  <el-select
                    v-model="cusromerFundPool"
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="cusromerQueryFundPool"
                    placeholder="请输入"
                    @change="handleStockSelect"
                  >
                    <div
                      v-infinite-scroll="diySearchLoad"
                      :infinite-scroll-disabled="diyQueryDisabled"
                      infinite-scroll-distance="200"
                    >
                      <el-option
                        v-for="item in cusromerFundPoolOptions"
                        :key="item.sConIrdcode"
                        :label="item.sConIrdname"
                        :value="item.sConIrdcode"
                      >
                        <!-- <span class="option-echeked">
                          <span @click.stop.native :label="item.sConIrdname">{{
                            item.sConIrdname
                          }}</span>
                        </span>
                        <span class="option-button">
                          <el-button
                            size="mini"
                            style="margin-left: 5px"
                            @click.stop="addItem(item)"
                          >
                            添加
                          </el-button>
                        </span> -->
                      </el-option>
                      <div v-if="diyQueryLoading" style="text-align: center; padding: 10px">
                        <el-icon><Loading /></el-icon>
                        <span>加载中...</span>
                      </div>
                      <div v-if="diyQueryNoMore" style="text-align: center; padding: 10px">
                        <span>没有更多数据了</span>
                      </div>
                    </div>
                  </el-select>
                  <!-- <el-button
                    type="primary"
                    style="margin-left: 10px"
                    size="mini"
                    @click="handleClick"
                    >确定</el-button
                  > -->
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="share-right">
          <div class="share-right-title">
            <div class="title">
              <span>自定义股票池</span>
            </div>
            <div class="empty" @click="clearCustomerList">
              <svg-icon name="del"></svg-icon>
              <span>清空</span>
            </div>
          </div>

          <div style="margin: 20px">
            <el-table :data="indexCustomerList" style="width: 100%" stripe height="420">
              <el-table-column prop="sConIrdcode" label="股票代码" align="center">
              </el-table-column>
              <el-table-column prop="sConIrdname" label="股票名称" align="center">
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template v-slot="scope">
                  <el-button type="text" @click="delCustomerList(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <div class="share-btn">
        <el-button type="primary" @click="searchCustomEtf">查找ETF</el-button>
      </div>
    </div>
    <div class="share-result divide-y-2" v-show="len > 0">
      <index-stock-share ref="indexShare" @goBack="goBack"></index-stock-share>
      <share-result ref="shareRes" @dataComplete="dataComplete"></share-result>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import shareResult from './shareResult.vue'
import IndexStockShare from './indexStockShare.vue'
import { getW1055050, getW1055051, getIndexSearch } from '@/api/etfpegging'
import { ElMessage } from 'element-plus'
import sensors from '@/utils/sensor/index'

const indexList = ref([])
const indexCustomerList = ref([])
const len = ref(0)
const selectedRows = ref([]) // 用于存储选中的行
const cusromerFundPoolOptions = ref([])
const cusromerFundPool = ref([])
const selectPageNum = ref(1)
const selectPageSize = ref(10)
const selectTotal = ref(0)
const selectLoading = ref(false)
const selectNoMore = computed(() => indexList.value?.length >= selectTotal.value)
const selectDisabled = computed(() => selectLoading.value || selectNoMore.value)
const diyQueryPageNum = ref(1)
const diyQueryPageSize = ref(10)
const diyQueryTotal = ref(0)
const diyQueryLoading = ref(false)
const diyQueryNoMore = computed(() => cusromerFundPoolOptions.value.length >= diyQueryTotal.value)
const diyQueryDisabled = computed(() => diyQueryLoading.value || diyQueryNoMore.value)

// 排序相关
const orderField = ref('iWeight') // 默认排序字段
const orderFlag = ref(0) // 默认降序
const handleSortChange = ({ column, prop, order }) => {
  if (prop === 'iWeight') {
    orderField.value = prop
    orderFlag.value = order === 'ascending' ? 1 : 0
    // 重置页码并重新加载数据
    selectPageNum.value = 1
    indexList.value = []
    debouncedQueryCustomList()
  }
}
//杀跌0单独处理
const fix2 = (val) => {
  if (val === 0) return '0'
  if (!val) return '--'
  return val.toFixed(2) + '%'
}
// 表格引用
const tableRef = ref(null)
const searchQuery = ref('')

const indexCode = ref('')
const indexCodeOptions = ref([])

const handleStockSelect = (selectedCode) => {
  // 根据选中的代码查找完整股票对象
  const selectedStock = cusromerFundPoolOptions.value.find(
    (item) => item.sConIrdcode === selectedCode,
  )

  if (!selectedStock) {
    ElMessage.error('未找到该股票信息')
    return
  }

  // 是否已存在
  const isExist = indexCustomerList.value.some((item) => item.sConIrdcode === selectedCode)

  if (isExist) {
    ElMessage.error('该股票已存在')
  } else {
    indexCustomerList.value.push({
      sConIrdcode: selectedStock.sConIrdcode,
      sConIrdname: selectedStock.sConIrdname,
    })
  }
}

onMounted(() => {
  indexCodeQuery()
  queryCustomList()
})

const indexCodeChange = () => {
  selectPageNum.value = 1 // 重置页码为1
  indexList.value = [] // 重置列表数据
  debouncedQueryCustomList()
}
const indexCodeQuery = (query) => {
  const params = {
    searchContent: '',
  }
  getIndexSearch(params).then((res) => {
    if (res?.data) {
      indexCodeOptions.value = res.data
    }
  })
}

// Watch for changes in cusromerFundPool and reset diyQueryPageNum
watch(searchQuery, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    diyQueryPageNum.value = 1
    cusromerFundPoolOptions.value = []
  }
})
//自定义查找股票
const cusromerQueryFundPool = async (query) => {
  searchQuery.value = query
  if (query !== '') {
    diyQueryLoading.value = true
    try {
      const params = {
        searchContent: searchQuery.value,
        showDelistFlag: 'N',
        stockType: 'ASHARE',
        currentPage: diyQueryPageNum.value,
        pageSize: diyQueryPageSize.value,
      }
      const res = await getW1055051(params)
      if (res?.data) {
        const newData = res?.data?.records.map((item) => ({
          sConIrdcode: item.sIrdcode,
          sConIrdname: item.sIrdname,
        }))
        if (diyQueryPageNum.value === 1) {
          cusromerFundPoolOptions.value = newData
        } else {
          cusromerFundPoolOptions.value = [...cusromerFundPoolOptions.value, ...newData]
        }
        diyQueryTotal.value = res.data.total
      }
    } finally {
      diyQueryLoading.value = false
    }
  }
}

/**
 * 处理用户滚动表格
 */
const handleScroll = (e) => {
  // 拖动横向滚动条则不处理
  if (e.scrollTop == 0) {
    return
  }

  // 可视区域的高度
  const scrollHeight = tableRef.value.$refs.bodyWrapper.scrollHeight
  // 表格的总高度，包括不可见部分
  const clientHeight = tableRef.value.$refs.tableBody.clientHeight

  // 是否触底判断
  const isBottom = scrollHeight + e.scrollTop >= clientHeight - 10

  if (isBottom) {
    console.log('表格滚动触底了')
    selectQueryloadMore()
  }
}

const queryCustomList = async () => {
  selectLoading.value = true
  try {
    const params = {
      searchContent: indexCode.value || '上证指数',
      currentPage: selectPageNum.value,
      pageSize: selectPageSize.value,
      orderField: orderField.value,
      orderFlag: orderFlag.value,
    }
    console.log('请求参数:', params)
    const res = await getW1055050(params)
    if (res?.data) {
      const newData = res.data.records
      selectTotal.value = res.data.total // 假设接口返回总条数字段

      if (selectPageNum.value === 1) {
        indexList.value = newData
      } else {
        indexList.value = [...indexList.value, ...newData]
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    selectLoading.value = false
    isLoadingMore.value = false // 重置状态标志
  }
}
const timeout = ref(null)
//定义去抖动函数
const debounce = (func, wait) => {
  return (...args) => {
    if (timeout.value) {
      clearTimeout(timeout.value)
    }
    timeout.value = setTimeout(() => func(...args), wait)
  }
}
//使用去抖动函数包裹查询方法
const debouncedQueryCustomList = debounce(queryCustomList, 500)

const isLoadingMore = ref(false) // 添加一个状态标志，防止重复加载
const selectQueryloadMore = () => {
  if (selectNoMore.value || isLoadingMore.value) return
  isLoadingMore.value = true // 设置为正在加载
  selectPageNum.value++ // 仅在加载更多时递增页码
  debouncedQueryCustomList()
}
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}
const addCustomerList = (row) => {
  if (indexCustomerList.value.length >= 10) {
    ElMessage.error('最大支持10只股票同时查询')
    return
  }
  // 判断是否已经存在
  if (indexCustomerList.value.some((item) => item.sConIrdcode === row.sConIrdcode)) {
    ElMessage.error('该股票已存在')
    return
  } else {
    indexCustomerList.value.push(row)
  }
}
const delCustomerList = (row) => {
  const index = indexCustomerList.value.findIndex((item) => item.sConIrdcode === row.sConIrdcode)
  if (index !== -1) {
    indexCustomerList.value.splice(index, 1)
  }
}
const clearCustomerList = () => {
  indexCustomerList.value = []
}

const diySearchLoad = () => {
  if (diyQueryNoMore.value || !cusromerFundPool.value) return
  diyQueryPageNum.value++
  cusromerQueryFundPool(searchQuery.value)
}
const addAllCustomerList = () => {
  selectedRows.value.forEach((row) => {
    if (!indexCustomerList.value.some((item) => item.sConIrdcode === row.sConIrdcode)) {
      indexCustomerList.value.push(row)
    }
  })
}
const addItem = (row) => {
  // 判断是否已经存在
  if (indexCustomerList.value.some((item) => item.sConIrdcode === row.sConIrdcode)) {
    ElMessage.error('该股票已存在')
    return
  } else {
    indexCustomerList.value.push(row)
  }
}
const shareRes = ref()
const indexShare = ref()
const searchCustomEtf = () => {
  if (indexCustomerList.value.length === 0) {
    ElMessage.error('请选择股票池')
    return
  }
  if (indexCustomerList.value.length >= 10) {
    ElMessage.error('最大支持10只股票同时查询')
    return
  }
  //indexList: 代码列表；isParent： true or flase 是否父组件调用
  shareRes.value.getData(indexCustomerList.value, true)
  indexShare.value.getData(indexCustomerList.value, true)

  sensors.track('zhitou_etfpegging_share', {
    button_name: 'ETF查找',
  })
}
const dataComplete = (val) => {
  len.value = val.length
}
const goBack = () => {
  len.value = 0
  indexList.value = []
  indexCode.value = ''
  indexCustomerList.value = []
  debouncedQueryCustomList()
}
</script>

<style lang="scss" scoped>
.share {
  display: flex;
  flex-direction: column;
  .share-box {
    display: flex;
    justify-content: center;

    .share-left {
      width: 480px;
      border: 1px solid #e8e8ef;
      margin-top: 24px;
      margin-bottom: 92px;
      margin-right: 16px;
      box-shadow:
        0 2px 4px 0 rgba(0, 0, 0, 0.12),
        0 0 6px 0 rgba(0, 0, 0, 0.04);
      .copy {
        cursor: pointer;
        margin-top: 10px;
        .svg-icon {
          color: #2468f2;
        }
        span {
          color: #2468f2;
        }
      }
      .custom-search {
        width: 100%;
        .custom-search-title {
          display: flex;
          justify-content: center;
          margin-top: 60px;
          span {
            font-family: Source Han Sans CN;
            font-size: 18px;
            font-weight: 700;
            color: #3f598c;
          }
        }
        .custom-search-input {
          margin-top: 20px;
          display: flex;
          :deep(.el-input--medium .el-input__inner) {
            width: 450px;
          }
        }
      }
      :deep(.el-tabs--border-card) {
        border: none;
        box-shadow: none;
      }
    }

    .share-right {
      width: 480px;
      margin-top: 24px;
      margin-bottom: 92px;
      background: #ffffff;
      border: 1px solid #dcdfe6;
      box-shadow:
        0 2px 4px 0 rgba(0, 0, 0, 0.12),
        0 0 6px 0 rgba(0, 0, 0, 0.04);
      .share-right-title {
        border: 1px solid #e8e8ef;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 39px;
        background: #f3f5fb;
        padding: 0 20px;
        .title {
          font-family: Source Han Sans CN;
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }
        .empty {
          cursor: pointer;
          span {
            color: #2468f2;
            font-family: Source Han Sans CN;
            font-size: 14px;
            font-weight: 350;
          }
          .svg-icon {
            color: #2468f2;
            width: 16px;
            height: 16px;
            margin-right: 4px;
          }
        }
      }
    }
  }
  .share-btn {
    display: flex;
    justify-content: center;
    margin-bottom: 40px;
  }
}

// .option-button {
//   display: none;
// }
// .el-select-dropdown__item {
//   display: flex;
//   justify-content: space-between;
// }
// .el-select-dropdown__item.hover,
// .el-select-dropdown__item:hover {
//   .option-button {
//     display: inline-block;
//   }
// }
</style>
